﻿using System;
using System.Collections.Generic;
using System.Linq;
using JStore.Core.Entities;
using JStore.Data.Daos;

namespace JStore.Tasks
{
    /// <summary>
    ///
    /// </summary>
    public class UserRoleTask
    {
        private readonly UserRoleDao _userRoleDao = new UserRoleDao();
        private readonly RoleMenuDao _roleMenuDao = new RoleMenuDao();
        private readonly RolePowerDao _rolePowerDao = new RolePowerDao();

        public List<UserRole> GetAll()
        {
            return _userRoleDao.GetAll();
        }

        public UserRole GetByRoleId(int roleId)
        {
            return _userRoleDao.GetByRoleId(roleId);
        }

        public void Create(string roleName, List<int> menuIds, List<int> powerIds)
        {
            var info = new UserRole
                           {
                               RoleName = roleName,
                           };
            var roleId = Convert.ToInt32(_userRoleDao.Add(info));

            var roleMenus = menuIds.Select(c => new RoleMenu { MenuId = c, RoleId = roleId }).ToList();
            var rolePowers = powerIds.Select(c => new RolePower { PowerId = c, RoleId = roleId }).ToList();

            foreach (var roleMenu in roleMenus)
                _roleMenuDao.Add(roleMenu);

            foreach (var rolePower in rolePowers)
                _rolePowerDao.Add(rolePower);
        }


        public void Update(int roleId, string roleName, List<int> menuIds, List<int> powerIds)
        {
            var roleInfo = _userRoleDao.GetByRoleId(roleId);
            if(roleInfo != null)
            {
                var roleMenus = menuIds.Select(c => new RoleMenu { MenuId = c, RoleId = roleId }).ToList();
                var rolePowers = powerIds.Select(c => new RolePower { PowerId = c, RoleId = roleId }).ToList();

                _roleMenuDao.DeleteByRoleId(roleId);
                _rolePowerDao.DeleteByRoleId(roleId);

                foreach (var roleMenu in roleMenus)
                    _roleMenuDao.Add(roleMenu);

                foreach (var rolePower in rolePowers)
                    _rolePowerDao.Add(rolePower);
            }
        }
         
    }
}

